package com.example.sdcardfiletest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.example.sdcardfiletest.R;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class NewActivity extends Activity {
	public static final int MODE= Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE;
    public static final String PREFERENCE_NAME="WX_SETING";
    private static String randomNumStr="";
	TextView tv1,tv2;
	Button saveBtn;
	 @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 super.onCreate(savedInstanceState);
	     setContentView(R.layout.activity_new);
	     tv1=(TextView) findViewById(R.id.textView1);
	     tv2=(TextView) findViewById(R.id.textView2);
	     saveBtn=(Button) findViewById(R.id.button1);
	     saveBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				saveSDCard();
			}
		});
	     
	}
	 private void saveSDCard(){
		 File file = new File("/sdcard/");
         String fileName= "zhanghao"+".txt";
         if (file.exists()&&file.canWrite()) {
             File newFile=new File(file.getAbsolutePath()+"/"+fileName);
             try{
                 if(newFile.createNewFile()){
                	 FileOutputStream  fileOutputStream=new FileOutputStream(newFile);
                     randomNumStr+=tv1.getText().toString()+"\n";
                     randomNumStr+=tv2.getText().toString()+"\n";
                     fileOutputStream.write(randomNumStr.getBytes());
                     fileOutputStream.flush();
                     fileOutputStream.close();
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
	 }
	 @Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		loadSharedPreference();
	}
	 private void loadSharedPreference(){
	        SharedPreferences sh=getSharedPreferences(PREFERENCE_NAME,MODE);
	        String username = sh.getString("username","");
	        tv1.setText(username);
	        String password = sh.getString("password","");
	        tv2.setText(password);
	 }

}
